<?php

namespace app\beautiful\controller\admin\appointment;

use app\BaseController;

use app\beautiful\model\appointment\AppointmentModel;

use app\beautiful\model\appointment\TechnicianModel;

use app\beautiful\model\appointment\TechnicianProjectModel;

use app\beautiful\model\appointment\TechnicianSchedulingModel;
use app\beautiful\model\project\ProjectModel;

use app\beautiful\model\project\ProjectTypeModel;

use app\beautiful\model\StaffModel;
use app\common\logic\DataLogic;
use think\Db;


class Technician extends BaseController {

    protected $name='技师';

    public function index()

    {
        $appointment_id=$this->request->param('appointment_id');

        $search=$this->request->param('search');

        $name=$this->request->param('name');

        $mobile=$this->request->param('mobile');

        $status=$this->request->param('status/d',1);

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['status','=',$status],

            ['is_delete','=',0]

        ];



        if(!empty($name)) $where[]=['name','=',$name];

        if(!empty($mobile)) $where[]=['mobile','=',$mobile];
        //指派技师时搜索
        if(!empty($search)) $where[]=['name|mobile','like','%'.$search.'%'];
        //根据预约分配技师
        if(!empty($appointment_id)){
            //用户预约
            $appointment_info = AppointmentModel::find($appointment_id);

            $start_totime=strtotime($appointment_info->day.' '.$appointment_info->start_time);

            $end_totime=strtotime($appointment_info->day.' '.$appointment_info->end_time);

            $start_time=(int)str_replace(':','',$appointment_info->start_time);

            $end_time=(int)str_replace(':','',$appointment_info->end_time);

            //技师排班
            $technician_arr=TechnicianSchedulingModel::withCount(['appointment'=>function($query){

                $query->where([

                    ['shop_id','=',$this->request->shopId],

                    ['status','in',[1,4,8]]

                ]);

            }])->where("day='{$appointment_info->day}' and CONVERT(REPLACE(start_time,':',''),SIGNED) <= '{$start_time}' and CONVERT(REPLACE(end_time,':',''),SIGNED)>={$end_time}")

                ->where(['project_id'=>$appointment_info->project_id])

                ->select()

                ->toArray();

            $technician_id_arr=[];

            foreach ($technician_arr as $k=>$v){
                if($v['appointment_count'] < $v['appointment_num']){
                    $technician_id_arr[]=$v['technician_id'];
                }
            }

            $where[] = ['technician_id', 'in', implode(',',$technician_id_arr)];

        }
        //$technician_model = new TechnicianModel();

        $technician_model = TechnicianModel::with(['staff'=>function($query){

            $query->field('staff_id,name,mobile');

        }]);

        if(!empty($appointment_id))   $technician_model = $technician_model->with(['schedulings']);

        $technician_model = $technician_model->withCount(['projects'=>function($query){

            $query->where([['is_delete','=',0]]);

        }]);

        $order=['add_time'=>'desc'];$field="*";$append=['add_time_format','tags_string','status_means'];

        $limit=$this->request->limit;$page=$this->request->page;

        $return = DataLogic::getDataList($technician_model,$where,$order,$field,$limit,$page,$append);





        foreach ($return['list'] as $key=>$vlaue){
            if(!empty($appointment_id)) {
                foreach ($vlaue['schedulings'] as $k => $v) {
                    //显示符合条件的排班
                    if (strtotime($v['day'] . ' ' . $v['start_time']) <= $start_totime && $end_totime <= strtotime($v['day'] . ' ' . $v['end_time'])) {

                        $return['list'][$key]['schedulings'] = $v;
                    }
                }
            }
            $return['list'][$key]['staff']=[
                'staff_id'=>$vlaue['staff']?$vlaue['staff']['staff_id']:0,
                'name'=>$vlaue['staff']?$vlaue['staff']['name']:'',
                'mobile'=>$vlaue['staff']?$vlaue['staff']['mobile']:'',
            ];
        }


        return $this->success($return);

    }


    public function show()

    {

        $technician_id=$this->request->param('technician_id/d',0);

        if($technician_id==0) return $this->success([]);



        if(null === $technician = TechnicianModel::with(['staff'=>function($query){

                $query->field('staff_id,name,mobile');

            }])
                ->find($technician_id)) {

            return $this->error($this->name.'不存在');
        }


        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($technician->is_delete != 0) return $this->error($this->name.'不存在');

        $staff = [
            'staff_id'=>$technician->staff?$technician->staff->staff_id:0,
            'name'=>$technician->staff?$technician->staff->name:'',
            'mobile'=>$technician->staff?$technician->staff->mobile:''
        ];

        $form=[

            'face'=>$technician->face,

            'name'=>$technician->name,

            'mobile'=>$technician->mobile,

            'position'=>$technician->position,

            'working_collar'=>$technician->working_collar,

            'job_number'=>$technician->job_number,

            'brief_introduction'=>$technician->brief_introduction,

            'staff'=>$staff,

        ];



        return $this->success(['form'=>$form]);

    }

    public function save()

    {

        $technician_id=$this->request->param('technician_id/d',0);

        $face=$this->request->param('face');

        $name=$this->request->param('name');

        $mobile=$this->request->param('mobile');

        $working_collar=$this->request->param('working_collar/d',0);

        $job_number=$this->request->param('job_number');

        $position=$this->request->param('position');

        $brief_introduction=$this->request->param('brief_introduction');

        $staff_id=$this->request->param('staff_id/d',0);


        //判断传来的参数

        if(empty($face)) return $this->error('请上传头像');

        if(empty($name)) return $this->error('请输入名称');

        if(empty($mobile) || !is_mobile($mobile)) return $this->error('请输入手机号');

        if(empty($working_collar) || $working_collar<=0) return $this->error('请输入工龄，且不能小于0');

        if(empty($job_number)) return $this->error('请输入工号');

        if(empty($position)) return $this->error('请输入职位');

        if(empty($brief_introduction) || mb_strlen($brief_introduction)>200) return $this->error('请输入简介，且字数不能多于200');

        if($staff_id<=0) return $this->error('请绑定员工');

        //判断员工是否存在和是否已被绑定
        if(null===$staff=StaffModel::where(['staff_id'=>$staff_id,'is_delete'=>0])->find()){

            return $this->error('员工不存在');
        }

        $bind_technician = TechnicianModel::where(['staff_id'=>$staff_id,'is_delete'=>0])->find();

        if(!empty($bind_technician) && $bind_technician->technician_id!==$technician_id) return $this->error('员工已经被绑定');

        //判断手机号与员工是否一致
        if($mobile!==$staff->mobile)  return $this->error('技师电话与员工不一致');

        if($technician_id != 0){

            if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');

            if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

            if($technician->status != 1) return $this->error($this->name.'不存在');

            if($technician->is_delete != 0) return $this->error($this->name.'不存在');

            $pre_face=$technician->face;

            //判断手机号的唯一性

            if($mobile != $technician->mobile){

                if(null !== TechnicianModel::where([

                        ['shop_id','=',$this->request->shopId],

                        ['status','=',1],

                        ['is_delete','=',0],

                        ['mobile','=',$mobile]

                    ])->find()){

                    return $this->error('该手机号已存在');

                }

            }

            //判断工号的唯一性

            if($job_number != $technician->job_number){

                if(null !== TechnicianModel::where([

                        ['shop_id','=',$this->request->shopId],

                        ['status','=',1],

                        ['is_delete','=',0],

                        ['job_number','=',$job_number]

                    ])->find()){

                    return $this->error('该工号已存在');

                }

            }

        }else{

            $technician = new TechnicianModel();

            $technician->shop_id = $this->request->shopId;

            $pre_face=null;

            //判断手机号的唯一性

            if(null !== TechnicianModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['status','=',1],

                    ['is_delete','=',0],

                    ['mobile','=',$mobile]

                ])->find()){

                return $this->error('该手机号已存在');

            }

            //判断工号的唯一性

            if(null !== TechnicianModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['status','=',1],

                    ['is_delete','=',0],

                    ['job_number','=',$job_number]

                ])->find()){

                return $this->error('该工号已存在');

            }

        }



        $technician->face=$face;

        $technician->name=$name;

        $technician->mobile=$mobile;

        $technician->position=$position;

        $technician->working_collar=$working_collar;

        $technician->job_number=$job_number;

        $technician->brief_introduction=$brief_introduction;

        $technician->staff_id=$staff_id;

        $technician->save();



        imgReplaceAct($face,$pre_face);

        return $this->success('操作成功');

    }



    public function quit()

    {

        $technician_id=$this->request->param('technician_id/d',0);

        if($technician_id==0) return $this->error($this->name.'不存在');

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');

        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($technician->is_delete != 0) return $this->error($this->name.'不存在');



        if($technician->status != 1) return $this->error($this->name.'已离职，请勿重复操作');



        //补充判断



        $technician->status = -1;

        $technician->save();

        return $this->success('离职成功');

    }



    public function del()

    {

        $technician_id=$this->request->param('technician_id/d',0);

        if($technician_id==0) return $this->error($this->name.'不存在');

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');

        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($technician->is_delete != 0) return $this->error($this->name.'不存在');



        if($technician->status != -1) return $this->error($this->name.'离职状态才可删除');



        //补充判断



        $technician->is_delete = 1;

        $technician->save();

        return $this->success('删除成功');

    }



    /********************************************************* start 技师详情  start **************************************************************/



    public function detail()

    {

        $technician_id=$this->request->param('technician_id/d',0);

        if($technician_id==0) return $this->error($this->name.'不存在');

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');

        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($technician->is_delete != 0) return $this->error($this->name.'不存在');



        $engaged_num=TechnicianProjectModel::where([

            ['shop_id','=',$this->request->shopId],

            ['technician_id','=',$technician_id]

        ])->sum('engaged_num') ?? 0;



        $projects_count=TechnicianProjectModel::where([

            ['shop_id','=',$this->request->shopId],

            ['technician_id','=',$technician_id],

            ['is_delete','=',0]

        ])->count() ?? 0;



        $detail=[

            'face'=>$technician->face,

            'name'=>$technician->name,

            'mobile'=>$technician->mobile,

            'working_collar'=>$technician->working_collar,

            'job_number'=>$technician->job_number,

            'brief_introduction'=>$technician->brief_introduction,

            'status'=>$technician->status,

            'status_means'=>$technician->status_means,

            'tags'=>$technician->tags ?? [],

            'engaged_num'=>$engaged_num,

            'projects_count'=>$projects_count,

        ];



        return $this->success(['detail'=>$detail]);

    }



    public function changTags()

    {

        $technician_id=$this->request->param('technician_id/d',0);

        $tags=$this->request->param('tags/a',[]);



        if($technician_id==0) return $this->error($this->name.'不存在');

        if(empty($tags) || !is_array($tags) || count($tags)==0) return $this->error('至少保留一个标签');



        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');

        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($technician->is_delete != 0) return $this->error($this->name.'不存在');



        $technician->tags=$tags;

        $technician->save();

        return $this->success('操作成功');

    }



    public function getTechnicianAppointmentList()

    {



        $technician_id=$this->request->param('technician_id/d',0);

        $status=$this->request->param('status/d',0);



        if($technician_id==0) return $this->error($this->name.'不存在');

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');

        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($technician->is_delete != 0) return $this->error($this->name.'不存在');



        $where=[

            ['shop_id','=',$this->request->shopId],

            ['technician_id','=',$technician_id],

        ];



        if(!empty($status)) $where[]=['status','=',$status];

        $appointment_model = new AppointmentModel();

        $appointment_model=$appointment_model->with(['member','technician']);

        $order=['add_time'=>'desc'];

        $field="*";

        $append=['add_time_format','status_means','operate_type_means','arrival_time_format','cancel_time_format'];

        $return = DataLogic::getDataList($appointment_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);

    }



    public function getTechnicianBindProjectList()

    {

        $technician_id=$this->request->param('technician_id/d',0);

        if($technician_id==0) return $this->error($this->name.'不存在');

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');

        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($technician->is_delete != 0) return $this->error($this->name.'不存在');



        $where=[

            ['shop_id','=',$this->request->shopId],

            ['technician_id','=',$technician_id],

            ['is_delete','=',0],

        ];



        $technician_project_model= new TechnicianProjectModel();

        $technician_project_model = $technician_project_model->with(['project']);

        $order=['add_time'=>'desc'];

        $field="*";

        $append=['add_time_format'];



        $return=DataLogic::getDataList($technician_project_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);



        return $this->success($return);

    }



    public function getProjectListFromTechnicianBind()

    {

        $technician_id=$this->request->param('technician_id/d',0);

        if($technician_id==0) return $this->error($this->name.'不存在');

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');

        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($technician->is_delete != 0) return $this->error($this->name.'不存在');



        $project_ids=TechnicianProjectModel::where([

            ['shop_id','=',$this->request->shopId],

            ['technician_id','=',$technician_id],

            ['is_delete','=',0],

        ])->column('project_id') ?? [];



        $where=[

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['project_id','not in',$project_ids]

        ];



        $project_model= new ProjectModel();

        $order=['add_time'=>'desc'];

        $field='*';

        $append=['add_time_format'];

        $return = DataLogic::getDataList($project_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);

    }



    public function technicianBindProject()

    {

        $technician_id=$this->request->param('technician_id/d',0);

        $project_ids=$this->request->param('project_ids/a',[]);



        if($technician_id==0) return $this->error($this->name.'不存在');

        if(empty($project_ids) || !is_array($project_ids)) return $this->error('请选择项目');



        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error($this->name.'不存在');

        if($technician->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($technician->is_delete != 0) return $this->error($this->name.'不存在');



        $bind_project_ids=TechnicianProjectModel::where([

                ['shop_id','=',$this->request->shopId],

                ['technician_id','=',$technician_id],

                ['is_delete','=',0],

            ])->column('project_id') ?? [];



        $project_ids = array_diff($project_ids,$bind_project_ids) ?? [];



        $project_ids = ProjectModel::where([

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['project_id','in',$project_ids]

        ])->column('project_id') ?? [];



        if(empty($project_ids)) return $this->error('请选择项目');

        $technician_project_data=[];

        foreach ($project_ids as $project_id){

            $technician_project_data[]=[

                'shop_id'=>$this->request->shopId,

                'project_id'=>$project_id,

                'technician_id'=>$technician_id

            ];

        }

        $technician_project_model= new TechnicianProjectModel();

        $technician_project_model->saveAll($technician_project_data);



        return $this->success('成功绑定');

    }



    public function delTechnicianProject()

    {

        $bind_id= $this->request->param('bind_id/d',0);

        if($bind_id==0) return $this->error('参数错误');

        if(null === $technician_project = TechnicianProjectModel::find($bind_id)) return $this->error('您未绑定这个项目');

        if($technician_project->shop_id != $this->request->shopId) return $this->error('您未绑定这个项目');

        if($technician_project->is_delete != 0) return $this->error('您未绑定这个项目');



        $technician_project->is_delete=1;

        $technician_project->save();

        return $this->success('删除成功');

    }





    /********************************************************* end 技师详情  end **************************************************************/





}

